"""
MUD 游戏界面模块

这个模块提供了一个可复用的 MUD 游戏界面类。
"""

from __future__ import annotations

# 导入必要的模块
from textual.app import App  # 导入Textual应用程序基类
from textual.widgets import Label, Button, Input, RichLog, Static, Header, Tree  # 导入各种UI组件
from textual.containers import Container, Horizontal, Vertical  # 导入容器组件
from textual.binding import Binding  # 导入按键绑定功能
from textual.screen import Screen  # 导入屏幕组件
from textual.widgets.tree import TreeNode  # 导入树节点组件
from rich.text import Text  # 导入富文本组件
from rich.style import Style  # 导入样式组件
from rich.console import Console  # 导入控制台组件
from typing import Callable, Optional  # 导入类型提示

class MudUI(App):
    """MUD 游戏界面主类"""
    
    # 定义快捷键绑定
    BINDINGS = [
        Binding("escape", "quit", "退出游戏"),
    ]
    
    # 定义界面样式
    CSS = """
    Screen {
        align: center middle;
    }
    
    #game-container {
        width: 100%;
        height: 100%;
        background: #1f1f1f;
        layout: grid;
        grid-size: 1;
        grid-rows: 85% 10% 5%;
        padding: 0;
    }
    
    #main-section {
        width: 100%;
        height: 100%;
        layout: horizontal;
        margin: 0;
        padding: 0;
    }
    
    #menu-tree {
        width: 15%;
        height: 100%;
        background: #2f2f2f;
        border-right: solid #3f3f3f;
        padding: 0;
        margin: 0;
    }
    
    Tree {
        background: #2f2f2f;
        color: #ffffff;
    }
    
    .tree--cursor {
        background: #3f3f3f;
        color: #ffffff;
    }
    
    #menu-tree-widget {
        background: #2f2f2f;
        color: #ffffff;
        scrollbar-size: 1 1;
    }
    
    #main-container {
        width: 85%;
        height: 100%;
        margin: 0;
        padding: 0;
    }
    
    #main-area {
        width: 70%;
        height: 100%;
        border-right: solid #3f3f3f;
        background: #2a2a2a;
        margin: 0;
        padding: 0;
    }
    
    #status-area {
        width: 30%;
        height: 100%;
        background: #2a2a2a;
        margin: 0;
        padding: 0;
    }
    
    #room-desc {
        height: 100%;
        padding: 1;
        margin: 0;
        color: #ffffff;
        scrollbar-size: 1 1;
        overflow-y: scroll;
        overflow-x: hidden;
    }
    
    #player-status {
        height: 100%;
        padding: 1;
        margin: 0;
        color: #ffffff;
        scrollbar-size: 1 1;
        overflow-y: scroll;
        overflow-x: scroll;
    }
    
    #game-log {
        width: 100%;
        height: 100%;
        margin: 0;
        border: none;
        background: #2f2f2f;
        color: #ffffff;
        padding: 0 1 0 1;
        scrollbar-size: 1 1;
        overflow-y: scroll;
        overflow: auto;
    }
    
    #command-input {
        width: 100%;
        height: 100%;
        border: none;
        background: #2f2f2f;
        color: #ffffff;
        padding: 0 1 0 1;
        margin: 0;
    }
    
    Label {
        width: 100%;
        color: #ffffff;
    }
    """
    
    def __init__(
        self,
        initial_room: str = "",
        initial_status: str = "",
        initial_message: str = "",
        *args,
        **kwargs
    ):
        super().__init__(*args, **kwargs)
        self._initial_room = initial_room
        self._initial_status = initial_status
        self._initial_message = initial_message
        self.on_command: Optional[Callable[[str], None]] = None
        self.on_menu: Optional[Callable[[str], None]] = None

    def compose(self):
        """创建游戏界面布局"""
        with Container(id="game-container"):
            # 创建主要区域
            with Container(id="main-section"):
                # 创建菜单树
                with Container(id="menu-tree"):
                    tree = Tree("菜单", id="menu-tree-widget")
                    tree.guide_style = "bold blue"
                    tree.root.expand()
                    
                    # 创建游戏菜单及其子项
                    game_node = tree.root.add("游戏", expand=True)
                    game_node.add_leaf("地图")
                    game_node.add_leaf("存档")
                    game_node.add_leaf("读档")
                    game_node.add_leaf("退出")
                    
                    # 创建角色菜单及其子项
                    char_node = tree.root.add("角色", expand=True)
                    char_node.add_leaf("属性")
                    char_node.add_leaf("装备")
                    char_node.add_leaf("称号")
                    
                    # 创建背包菜单及其子项
                    bag_node = tree.root.add("背包", expand=True)
                    bag_node.add_leaf("物品")
                    bag_node.add_leaf("消耗品")
                    bag_node.add_leaf("任务物品")
                    
                    # 创建技能菜单及其子项
                    skill_node = tree.root.add("技能", expand=True)
                    skill_node.add_leaf("战斗技能")
                    skill_node.add_leaf("生活技能")
                    
                    # 创建设置菜单及其子项
                    settings_node = tree.root.add("设置", expand=True)
                    settings_node.add_leaf("音效")
                    settings_node.add_leaf("显示")
                    settings_node.add_leaf("快捷键")
                    
                    # 创建帮助菜单及其子项
                    help_node = tree.root.add("帮助", expand=True)
                    help_node.add_leaf("游戏指南")
                    help_node.add_leaf("新手教程")
                    help_node.add_leaf("关于")
                    yield tree
                
                # 创建主要内容区域
                with Horizontal(id="main-container"):
                    # 创建游戏主显示区域
                    with Container(id="main-area"):
                        yield RichLog(id="room-desc")
                    # 创建玩家状态区域
                    with Container(id="status-area"):
                        yield RichLog(id="player-status")
            
            # 创建游戏日志区域
            yield RichLog(id="game-log")
            
            # 创建命令输入区域
            yield Input(placeholder="输入命令 (例如: look, go north, get sword)", id="command-input")
            
    def on_mount(self) -> None:
        """当UI组件完全加载后执行初始化"""
        self.title = "福禄 MUD"
        if self._initial_room:
            self.update_room(self._initial_room)
        if self._initial_status:
            self.update_status(self._initial_status)
        if self._initial_message:
            self.write_log(self._initial_message)
    
    def on_tree_node_selected(self, event: Tree.NodeSelected) -> None:
        """处理菜单项选择事件"""
        if len(event.node.children) == 0:
            self.handle_menu_click(event.node.label)
    
    def on_input_submitted(self, event: Input.Submitted) -> None:
        """处理命令输入事件"""
        command = event.value.strip().lower()
        if command and self.on_command:
            self.write_log(f"> {command}", style="bold yellow")
            self.on_command(command)
        event.input.value = ""

    def write_log(self, message: str, style: str = None) -> None:
        """写入日志消息"""
        game_log = self.query_one("#game-log")
        if isinstance(message, (Text, str)):
            if style and isinstance(message, str):
                message = Text(message, style=style)
            game_log.write(message)
        game_log.scroll_end()

    def create_styled_text(self, *segments) -> Text:
        """创建带样式的文本
        Args:
            segments: 文本片段，每个片段是一个元组 (text, style)
                     style 可以是 None，表示使用默认样式
        Example:
            text = ui.create_styled_text(
                ("普通文本", None),
                ("红色文本", "red"),
                ("粗体绿色文本", "bold green")
            )
        """
        result = Text()
        for text, style in segments:
            result.append(text, style=style)
        return result

    def update_room(self, description: str | Text, style: str = None) -> None:
        """更新房间描述
        Args:
            description: 描述文本，可以是字符串或Text对象
            style: 样式，例如 'red', 'bold green', 'blue', 'yellow' 等
        """
        room_log = self.query_one("#room-desc")
        room_log.clear()
        if isinstance(description, str) and style:
            description = Text(description, style=style)
        room_log.write(description)
        room_log.scroll_end()

    def update_status(self, status: str | Text, style: str = None) -> None:
        """更新玩家状态
        Args:
            status: 状态文本，可以是字符串或Text对象
            style: 样式，例如 'red', 'bold green', 'blue', 'yellow' 等
        """
        status_log = self.query_one("#player-status")
        status_log.clear()
        if isinstance(status, str) and style:
            status = Text(status, style=style)
        status_log.write(status)
        status_log.scroll_end()

    def on_key(self, event) -> None:
        """处理键盘事件"""
        if event.key == "escape":
            self.exit()
            
    def handle_menu_click(self, menu_item: str) -> None:
        """处理菜单点击事件"""
        if self.on_menu:
            self.on_menu(menu_item)
    
        if menu_item == "关于":
            try:
                with open("model/config/about.txt", encoding='utf-8') as f:
                    about_txt = f.read()
                self.write_log("正在打开关于信息...", style="yellow")
                self.update_room(about_txt)
                self.write_log("关于信息已显示", style="green")
            except Exception as e:
                print("错误:", str(e))
                self.write_log(f"显示关于信息时出错: {str(e)}", style="red")
    
    